package cn.rocky.structures.graph;

import cn.rocky.structures.array_list.ArrayList;
import cn.rocky.structures.array_list.List;

/**
 * 深度优先遍历
 */
public class GraphDFS {

    private Graph graph;

    private ArrayList<Integer> pre  = new ArrayList<>();

    private ArrayList<Integer> post = new ArrayList<>();

    private boolean[] visited;

    public GraphDFS(Graph graph) {
        this.graph = graph;
        visited = new boolean[graph.getV()];
        for (int i = 0; i < graph.getV(); i++) {
            if (!visited[i]) {
                dfs(i);
            }
        }
    }

    private void dfs(int v) {
        visited[v] = true;
        // 深度优先,前序遍历
        pre.add(v);
        for (int w : graph.adj(v)) {
            if (!visited[w]) {
                dfs(w);
            }
        }
        // 深度优先, 后序遍历
        post.add(v);
    }

    public ArrayList<Integer> pre() {
        return pre;
    }

    public ArrayList<Integer> post() {
        return  post;
    }

    public static void main(String[] args) {
        Graph graph = new Graph(7, 6);
        graph.insert(0, 1);
        graph.insert(0, 3);
        graph.insert(1, 2);
        graph.insert(1, 5);
        graph.insert(2, 4);
        graph.insert(2, 6);
        GraphDFS dfs = new GraphDFS(graph);
        System.out.println(graph);

        System.out.println(dfs.pre());
        System.out.println(dfs.post());
    }
}
